<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/7/10
 * Time: 下午5:56
 */

namespace app\apitemp\controller;

use app\common\controller\FeiePrint;
use app\common\controller\TemplateMsg;
use app\common\model\Merchant;
use app\common\model\Paylog;


class Lftpay extends Pub
{
    public $version="1.0";
//    public $partner_id="18060410173207886";
    public $input_charset="UTF-8";
//    public $core_merchant_no="EW_N5772984681";
    public $sign_type="MD5";
//    public $partner_key="78bc1ac50be17004b58edea930c70c78";
    public $submit_url="http://newfront.liantuobank.com/NewFront/base/gateway.in";
    public function pay($param, $pays)
    {
//        return $param;
        $kt = substr($param['auth_code'], 0, 2);
        $channel = "";
        if ($kt >= 25 && $kt <= 30) {
            $channel = "ALI";
            $pay_fs=3;
        } elseif ($kt >= 10 && $kt <= 15) {
            $channel = "WX";
            $pay_fs=2;
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '条码格式错误';
        }
        if (!empty($channel)) {
            $Paylog = new Paylog();
            $pays['orderid'] = $param['orderid'];
            $pays['pay_fs'] = $pay_fs;
            $Paylog->save($pays);
            $User = new Merchant();
            $machinfos = $User->where(array('id' => $param['merchantid']))->find();
            $head["service"] = "front.micropay";//扫码--被扫支付
            $head["version"] = $this->version;//默认版本号
            $head["partner_id"] =$machinfos['lft_pid'];//联富通线下提供pid
            $head["input_charset"] = $this->input_charset; //编码格式，默认只支持UTF-8
            $head["core_merchant_no"] = $machinfos['lft_core_merchant_no'];//联富通后台核心商户编号
            $head["sign_type"] = $this->sign_type;//加密方式，默认只支持MD5

            $body["merchant_no"] = $machinfos['lft_merchant_no']; //门店商户编号
            $body["channel_type"] = $channel;//支付渠道
            $body["out_trade_no"] = $param['orderid'];//商户订单号
            $body["total_amount"] = $param['total_fee']; //订单总金额
            $body["subject"] = "快捷支付";//商品标题
            $body["spbill_create_ip"] = $param['client_ip'];//终端IP
            $body["device_info"] = $param['device_id'];//设备号
            $body["auth_code"] = $param['auth_code'];//支付授权码134916225958156985


            $signArray = array_merge($head, $body);
            $sign = $this->createSign($signArray, $machinfos['lft_key']);
            $head["sign"] = $sign;

            $requestJson["body"] = $body;
            $requestJson["head"] = $head;
            $requestPara["requestJson"] = json_encode($requestJson);
            $resp = $this->requestAsHttpPOST($requestPara, $this->submit_url); //发送请求
            $re_msg = json_decode($resp, true);
            $arrc = $this->pay_statu($re_msg['body'],$param['merchantid'], $param['orderid']);

            return $arrc;

        }
    }

    public function checkpay($param)
    {
        try {
            $orderid = $param['out_trade_no'];

            $id = $param['merchantid'];
            $payxml = $this->orderquery($id, $orderid);

            $rarr = $this->pay_statu($payxml, $param['merchantid'],$orderid, "checkpay");

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }

        return $rarr;
    }
    private function orderquery($id, $orderid)
    {
        $User = new Merchant();
        $machinfos = $User->where(array('id' => $id))->find();
        $head["service"] = "front.query";//订单查询API
        $head["version"] = $this->version;//默认版本号
        $head["partner_id"] = $machinfos['lft_pid'];//联富通线下提供pid
        $head["input_charset"] = $this->input_charset; //编码格式，默认只支持UTF-8
        $head["core_merchant_no"] = $machinfos['lft_core_merchant_no'];//联富通后台核心商户编号
        $head["sign_type"] = $this->sign_type;//加密方式，默认只支持MD5


        $body["out_trade_no"] = $orderid;//商户订单号
//        $body["trade_no"]            ="00060011806081011119020239178664";//交易流水号,支付请求返回结果参数

        $signArray = array_merge($head, $body);
        $sign = $this->createSign($signArray, $machinfos['lft_key']);
        $head["sign"] = $sign;

        $requestJson["body"] = $body;
        $requestJson["head"] = $head;
        $requestPara["requestJson"] = json_encode($requestJson);
        $resp = $this->requestAsHttpPOST($requestPara, $this->submit_url); //发送请求

        $re_msg = json_decode($resp, true);
        return $re_msg['body'];

    }

    private function pay_statu($param,$id, $orderid, $type = "pay")
    {
        $Paylog = new Paylog();
        $payinfoa = $Paylog->where(['orderid' => $orderid])->find();
        if ($type == "checkpay") {
            if ($param['is_success'] == "S") {
                if ($param['trade_status'] == "success") {
                    $pays['orderno'] = $param['pay_channel_trade_no'];
                    $pays['pay_time'] = $param['gmt_payment'];
                    $pays['pay_statu'] = 1;
                    $pays['openid'] = isset($param['openid']) ? $param['openid'] : "";;
                    $pays['sub_openid'] = isset($param['sub_openid']) ? $param['sub_openid'] : "";
                    $pays['payinfo'] = json_encode($param);
                    $pays['price'] = $param['total_amount'];
                    $pays['trade_no'] = $param['pay_channel_out_trade_no'];
                    $Pub = new Pub();
                    $pays['service_charge'] = $Pub->service_charge($payinfoa['mid'], $pays['price'], $payinfoa['pay_fs']);
                    $Paylog->save($pays, array('orderid' => $payinfoa['orderid']));
                    $TemplateMsg = new TemplateMsg();
                    $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                    $FeiePrint=new FeiePrint();
                    $FeiePrint->sendprint($orderid);
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "SUCCESS";

                    $arrc['return_msg'] = "支付成功";
                    $arrc['result_msg'] = "支付成功";
                    $arrc['out_trade_no'] = $param['out_trade_no'];
                    $arrc['trade_no'] = $param['trade_no'];
                    $arrc = $this->getorderinfo($orderid);
                    return $arrc;
                }elseif($param['trade_status'] == "paying"){
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "USERPAYING";
                    $arrc['return_msg'] = "等待用户输入密码";
                    $arrc['result_msg'] = "等待用户输入密码";
                    $arrc['out_trade_no'] = $payinfoa['orderid'];
                    $arrc['trade_no'] = $payinfoa['trade_no'];
                }elseif($param['trade_status']=="closed"){

                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "";
                    $arrc['result_msg'] = "订单已关闭";
                    $arrc['out_trade_no'] = $payinfoa['orderid'];
                    $arrc['trade_no'] = $payinfoa['trade_no'];
                }elseif($param['trade_status']=="cancel"){

                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "";
                    $arrc['result_msg'] = "订单已撤销";
                    $arrc['out_trade_no'] = $payinfoa['orderid'];
                    $arrc['trade_no'] = $payinfoa['trade_no'];
                }else{

                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "";
                    $arrc['result_msg'] = "未知订单状态".$param['trade_status'];
                    $arrc['out_trade_no'] = $payinfoa['orderid'];
                    $arrc['trade_no'] = $payinfoa['trade_no'];
                }

            }
        } else {

            if ($param['is_success'] == "S") {

                $pays['orderno'] = $param['pay_channel_trade_no'];
                $pays['pay_time'] = $param['gmt_payment'];
                $pays['pay_statu'] = 1;
                $pays['openid'] = isset($param['openid']) ? $param['openid'] : "";;
                $pays['sub_openid'] = isset($param['sub_openid']) ? $param['sub_openid'] : "";
                $pays['payinfo'] = json_encode($param);
                $pays['price'] = $param['total_amount'];
                $pays['trade_no'] = $param['pay_channel_out_trade_no'];
                $Pub = new Pub();
                $pays['service_charge'] = $Pub->service_charge($payinfoa['mid'], $pays['price'], $payinfoa['pay_fs']);
                $Paylog->save($pays, array('orderid' => $payinfoa['orderid']));
                $TemplateMsg = new TemplateMsg();
                $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                $FeiePrint=new FeiePrint();
                $FeiePrint->sendprint($orderid);
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "SUCCESS";

                $arrc['return_msg'] = "支付成功";
                $arrc['result_msg'] = "支付成功";
                $arrc['out_trade_no'] = $param['out_trade_no'];
                $arrc['trade_no'] = $param['trade_no'];
                $arrc = $this->getorderinfo($orderid);
                return $arrc;

            } elseif ($param['is_success'] == "P") {
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "USERPAYING";
                $arrc['return_msg'] = "等待用户输入密码";
                $arrc['result_msg'] = "等待用户输入密码";
                $arrc['out_trade_no'] = $payinfoa['orderid'];
                $arrc['trade_no'] = $payinfoa['trade_no'];
            } elseif ($param['is_success'] == "F") {
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "FAIL";
                $arrc['return_msg'] = "";
                $arrc['result_msg'] = $param['error'] . $param['message'];
            }else{

                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "FAIL";
                $arrc['return_msg'] = "";
                $arrc['result_msg'] = "未知订单状态".$param['trade_status'];
                $arrc['out_trade_no'] = $payinfoa['orderid'];
                $arrc['trade_no'] = $payinfoa['trade_no'];
            }
        }
        return $arrc;


    }


}